require_relative 'CPFService'
require_relative 'Multipart'
require_relative 'StringUtils'

class UploadService < CPFService
	include Multipart
	include StringUtils
	UPLOAD_GATEWAY = "#{@@properties['serverurl']}/cordys/com.eibus.web.tools.upload.Upload.wcp"
	METHODXML = "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP:Body><UploadFile xmlns=\"http://schemas.cordys.com/bsf/uc/webapps/1.0/ucappsutil\"><type>{type}</type><fileName>{fileName}</fileName><filePath>{filePath}</filePath><componentPath>{componentPath}</componentPath></UploadFile></SOAP:Body></SOAP:Envelope>"

	def initialize assertion
		super assertion, UPLOAD_GATEWAY
		@formDataMap = {}
		@formDataMap["file1"] = nil
		@formDataMap["methodXML"] = ""	
		@formDataMap["encode"] = "true"
		@formDataMap["xmlcontent"] = "true"
		@formDataMap["organizationalcontext"] = "#{@@properties['organizationalContext']}"
		@formDataMap["timeout"] = "300000000"
		@formDataMap["contentType"] = "application/octet-stream"
		@formDataMap["receiver"] = ""
		@formDataMap["resultHtml"] = ""
	end

	def upload file, uploadFileName
		requestMap = {}
		requestMap[/\{type\}/] = @@properties["type"]
		requestMap[/\{fileName\}/] = "#{uploadFileName}.js"
		requestMap[/\{componentPath\}/] = @@properties["componentPath"]
		requestMap[/\{filePath\}/] = @@properties["filePath"]
		@formDataMap["methodXML"] = replaceMap METHODXML, requestMap
		@formDataMap["file1"] = file
		data, requestHeaders = Multipart::Post.prepare_query(@formDataMap)
		@request = data
		@headers = requestHeaders
		fireService
	end

	def url
		relative_url = getFromResponse(".//*[local-name() = 'FilePath']")[0]
		return "#{@@properties['serverurl']}#{relative_url}"
	end
end
